//
//  ViewController.m
//  An_Minh_Dat
//
//  Created by phan hoang quoc an on 4/21/15.
//  Copyright (c) 2015 phan hoang quoc an. All rights reserved.
//

#import "ViewController.h"
#import "Cell.h"

@interface ViewController ()
@property (strong,nonatomic)NSString *recipeID;
@property (strong,nonatomic)NSString *APIkey;
@property (strong,nonatomic)NSArray *photos;
// Minh start code
@property (strong, nonatomic) NSArray* appArr;

// Minh end code
@end

@implementation ViewController

- (void)viewDidLoad {
    //nut back
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]initWithTitle:@"Recipies" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.backBarButtonItem = backButton;
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    _APIkey = @"11b98252974bfa489035a46f02333101";
    NSString *urlString = [NSString stringWithFormat:@"http://food2fork.com/api/search?key=%@",self.APIkey];
    
    // Minh start code
    UILabel* titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    titleLabel.font = [UIFont fontWithName:@"American typewriter" size:20.0f];
    titleLabel.textAlignment = UITextAlignmentCenter;
    titleLabel.text = @"Recipes";
    
    self.navigationItem.titleView = titleLabel;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:245/256.0 green:166/256.0f blue:35/256.0f alpha:1];
    // Minh end code
    
    
    NSURL *url = [[NSURL alloc]initWithString:urlString];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:30];
    
    [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (!connectionError) {
            
            NSError *error;
            NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
            if (!error) {
                NSArray *photoDictionary = [dictionary objectForKey:@"recipes"];
                //NSLog(@"----------%@",photoDictionary);
                // Minh start code:
                self.appArr = photoDictionary;
                // End code
                
                self.photos = photoDictionary;
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.myTableView reloadData];
                });
                
            
            }
        }else{
            NSLog(@"connectionError =%@",connectionError);
        }
    }];
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *identifier = @"Cell";  // <--- cho nay ten identifier chua dung, minh chua sua Dat sua lai va lam tip phan show san ra nha, con phan day du lieu qua ben view2, minh da lam xong
    Cell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell==nil) {
        [tableView registerClass:[Cell class] forCellReuseIdentifier:identifier];
        cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    }
    NSDictionary *items = self.photos[indexPath.row];
    NSLog(@"==============%@", items);
    
    
    //Dat---->>
    cell.myLabel1.text = items[@"title"];
    cell.myLabel2.text = items[@"publisher"];
    cell.imgLink = items[@"image_url"];
    cell.myImageView.image = nil;
    NSString *urlString = [items objectForKey:@"image_url"];
    dispatch_async(dispatch_queue_create("image dowload", 0), ^{
        NSURL *url = [NSURL URLWithString:urlString];
        NSData *data = [[NSData alloc]initWithContentsOfURL:url];
        
        UIImage *images = [UIImage imageWithData:data];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if ([cell.imgLink isEqualToString:urlString]) {
                cell.myImageView.image = images;
            }
            
        });
        
    });
    //<<-----Dat
    
    
    
    // Minh start code
    int rate = [items[@"social_rank"] intValue];
    if (rate <= 40 && rate >= 11) {
        cell.rateStar3.image = [UIImage imageNamed:@"star-fill.png"];
    }
    if (rate <= 70 && rate >= 41) {
        cell.rateStar3.image = [UIImage imageNamed:@"star-fill.png"];
        cell.rateStar2.image = [UIImage imageNamed:@"star-fill.png"];
    }
    if (rate <= 100 && rate >= 71) {
        cell.rateStar3.image = [UIImage imageNamed:@"star-fill.png"];
        cell.rateStar2.image = [UIImage imageNamed:@"star-fill.png"];
        cell.rateStar1.image = [UIImage imageNamed:@"star-fill.png"];
    }
    
    // Minh end code.
    
    return cell;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}


- (IBAction)reloadButClick:(UIBarButtonItem *)sender {
    [self.myTableView reloadData];
}

// Minh code de gui dicDetails va indexPathRow cho view2, Dat dung xoa.
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    View2* details = [segue destinationViewController];
    NSIndexPath* indexPath = self.myTableView.indexPathForSelectedRow;
    
    long row = indexPath.row;
    details.appArr_View2 = self.appArr;
    details.indexRow_view2 = row;
    
    
}




-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *myArray = self.photos;
    return myArray.count;
}
    
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
